public class RomanNumberConverter {
  private static int simpleConvert(char roman) throws IllegalArgumentException {
    if(roman == 'I') return 1;
    if(roman == 'V') return 5;
    if(roman == 'X') return 10;
    if(roman == 'L') return 50;
    if(roman == 'C') return 100;
    if(roman == 'D') return 500;
    if(roman == 'M') return 1000;

    throw new IllegalArgumentException();
  }


  public static int convert(String romanNumber) throws IllegalArgumentException{
    int result = 0;
    int repetition = 0;
    try{
      for (int i = 0; i < romanNumber.length() - 1; i++){
        int currentValue = simpleConvert(romanNumber.charAt(i));
        int nextValue = simpleConvert(romanNumber.charAt(i + 1));
        if (currentValue >= nextValue){ 
          result += currentValue;
        }
        else{
          result -= currentValue;
        }

        if (currentValue == nextValue){
          repetition++;
          if ((repetition == 3) && (currentValue != 1000)){
            throw new IllegalArgumentException();
          }
        }
        else{
          repetition = 0;
        }
      }
      result += simpleConvert(romanNumber.charAt(romanNumber.length() - 1));

      return result;
    } catch (IllegalArgumentException e){
      throw e;
    }
  }

  public static String convert(int number) throws IllegalArgumentException {
    if (number <= 0){
      throw new IllegalArgumentException();
    }
    int valeur[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
    String roman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    int repetition = 0;
    String result = "";

    for(int i = 0; i < valeur.length; i++) {
      repetition = number / valeur[i];

      for(int j = 0; j < repetition; j++) {
        result = result + roman[i]; 
      }
      number = number - repetition * valeur[i];
    }
    return result;
  
  }
}
